# application/mapper/detection/mistake.py
import datetime
from application.extensions.databases import db
from application.extensions.logging import system_logger
from application.models.detection.mistake import Mistake
from typing import List, Dict, Any


class MistakeMapper:
    """错误数据访问层"""

    @staticmethod
    def get_mistake_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> tuple:
        """
        分页获取错误数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (错误数据列表, 总数)
        """
        query = db.session.query(Mistake).filter(Mistake.del_flag == "0")

        # 添加查询条件
        if conditions:
            if conditions.get("productId"):
                query = query.filter(Mistake.product_id == conditions["productId"])
            if conditions.get("mistakeType"):
                query = query.filter(Mistake.mistake_type == conditions["mistakeType"])
            if conditions.get("mistakeName"):
                query = query.filter(
                    Mistake.mistake_name.like(f"%{conditions['mistakeName']}%")
                )
            if conditions.get("mistakeNo"):
                query = query.filter(
                    Mistake.mistake_name.like(f"%{conditions['mistakeNo']}%")
                )
            # 可以根据实际需求添加更多查询条件

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page_num - 1) * page_size
        mistake_list = (
            query.order_by(Mistake.create_time.desc())
            .offset(offset)
            .limit(page_size)
            .all()
        )

        return mistake_list, total

    @staticmethod
    def create_mistake(mistake: Mistake) -> Mistake:
        """
        创建错误记录
        :param mistake: 错误对象
        :return: 创建后的错误对象
        """
        db.session.add(mistake)
        db.session.commit()
        return mistake

    @staticmethod
    def update_mistake(mistake: Mistake) -> Mistake:
        """
        更新错误记录
        :param mistake: 错误对象
        :return: 更新后的错误对象
        """
        db.session.commit()
        return mistake

    @staticmethod
    def get_all_mistakes() -> List[Mistake]:
        """
        获取所有错误记录
        :return: 错误记录列表
        """
        return db.session.query(Mistake).filter(Mistake.del_flag == "0").all()

    @staticmethod
    def get_mistake_by_id(mistake_id: int) -> Mistake:
        """
        根据ID获取错误记录
        :param mistake_id: 错误ID
        :return: 错误对象
        """
        return (
            db.session.query(Mistake).filter(Mistake.mistake_id == mistake_id).first()
        )
  
    @staticmethod
    def batch_delete_mistake(mistake_ids: list) -> int:
        """
        批量逻辑删除绕组
        :param mistake_ids: 误差Id列表
        :return: 删除的记录数
        """
        try:
            # 执行批量逻辑删除，将 del_flag 设置为 1
            updated_count = db.session.query(Mistake).filter(
                Mistake.mistake_id.in_(mistake_ids),
                Mistake.del_flag == 0  # 只更新未删除的记录
            ).update(
                {Mistake.del_flag: 1},
                synchronize_session=False
            )
            
            db.session.commit()
            return updated_count
        except Exception as e:
            db.session.rollback()
            system_logger.error(f"批量逻辑删除绕组失败: {e}")
            raise e
